package com.dayu.finecomm.protocol.cjj;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.protocol.codec.FixedLengthCheckMagicDecoder;
import com.dayu.finecomm.protocol.codec.Protocol;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.protocol.pojo.TPacket.VType;
import com.dayu.finecomm.protocol.pojo.TSensor;

import io.netty.buffer.ByteBuf;

/**
 * @ClassName: ZZJDecoder
 * @Description:针织机协议
 * @author: 戴卫国
 * @date: 2018年2月23日 下午4:34:21
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
@Protocol(ZZJDecoder.PROTO)
public class ZZJDecoder extends FixedLengthCheckMagicDecoder<TPacket> {

	static final String PROTO = "ZZJ";

	static Logger LOGGER = LoggerFactory.getLogger(ZZJDecoder.class);

	public ZZJDecoder() {

		super(new byte[] { (byte) 0x5c, (byte) 0x5c }, new byte[] { (byte) 0x5e, (byte) 0x5e }, 0, 2, 1);
	}

	@Override
	public TPacket unpack(ByteBuf in) {
		// TODO Auto-generated method stub
		in.skipBytes(2); // 5C 5C
		int length = in.readUnsignedByte() * 256 + in.readUnsignedByte(); // length

		long sTime = new Date().getTime();
		TPacket s = new TPacket(VType.PPP, PROTO, "", sTime);
		for (; in.readerIndex() <= length - 3;) {
			String sn = in.readUnsignedShort() + "";
			int type = in.readUnsignedByte() / 10;
			TPacket s1 = new TPacket(VType.PPP, PROTO, "", sTime);
			s.packets.add(s1);
			switch (type) {
			case 0x00:
				int val = in.readUnsignedByte() * 256 + in.readUnsignedByte();
				s1.sensors.add(new TSensor(sn, "V", val, sTime));
				s1.sensors.add(new TSensor(sn, "K", in.readUnsignedByte(), sTime));
				s1.sensors.add(new TSensor(sn, "S", in.readUnsignedByte(), sTime));
				break;
			case 0xAA:
				int size = in.readUnsignedByte();
				for (int i = 0; i < size; i++) {
					s1.sensors
							.add(new TSensor(sn, "L" + i, in.readUnsignedByte() * 256 + in.readUnsignedByte(), sTime));
					s1.sensors
							.add(new TSensor(sn, "V" + i, in.readUnsignedByte() * 256 + in.readUnsignedByte(), sTime));
				}
				s1.sensors.add(new TSensor(sn, "S", in.readUnsignedByte(), sTime));
				break;
			default:
				return null;
			}
		}

		return s;
	}

	@Override
	public byte[] echo() {
		// TODO Auto-generated method stub
		return null;
	}

}
